#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的文本转回答API
提供简洁的接口用于文本转回答功能
"""

import json
import logging
from text_to_response_service import TextToResponseService

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class SimpleTextAPI:
    """简单的文本转回答API"""
    
    def __init__(self, config_path: str = "config.json"):
        """初始化API"""
        self.service = TextToResponseService(config_path)
        logger.info("简单文本API初始化完成")
    
    def ask(self, question: str, stream: bool = False, 
           enable_web_search: bool = False) -> str:
        """
        提问并获取回答
        
        Args:
            question: 用户问题
            stream: 是否使用流式输出
            enable_web_search: 是否启用网络搜索
            
        Returns:
            str: AI回答
        """
        return self.service.get_response(question, stream, enable_web_search)
    
    def clear_history(self):
        """清空对话历史"""
        self.service.clear_history()
    
    def get_history(self):
        """获取对话历史"""
        return self.service.get_history()


def demo():
    """演示API使用"""
    print("=== 简单文本转回答API演示 ===")
    
    # 创建API实例
    api = SimpleTextAPI()
    
    # 测试问题
    questions = [
        "你好，你是谁？",
        "请解释一下机器学习",
        "推荐一个Python学习资源"
    ]
    
    for i, question in enumerate(questions, 1):
        print(f"\n--- 问题 {i} ---")
        print(f"问: {question}")
        print("答: ", end="")
        
        try:
            answer = api.ask(question, stream=False)
            print(answer)
        except Exception as e:
            print(f"错误: {e}")
    
    # 显示对话历史
    print(f"\n--- 对话历史 ---")
    history = api.get_history()
    for i, msg in enumerate(history):
        role = "用户" if msg["role"] == "user" else "助手"
        content = msg["content"][:50] + "..." if len(msg["content"]) > 50 else msg["content"]
        print(f"{i+1}. {role}: {content}")


if __name__ == "__main__":
    demo()
